import { Head } from "fresh/runtime";
import { page, type PageProps } from "fresh";
import { find } from "utils/db.ts";
import { define } from "utils/state.ts";
import PostList from "../../islands/PostList.tsx";
import ThemeToggle from "../../islands/ThemeToggle.tsx";
import PageContainer from "../../components/layout/PageContainer.tsx";

interface UserPageProps {
  userName: string;
  posts: {
    id: string;
    title: string;
    content: string;
    shared: boolean;
    hasPassword: boolean;
  }[];
  notFound: boolean;
}

export const handler = define.handlers({
  GET(ctx) {
    const name = ctx.params.name;
    const user = find("User", { name }, ["id"]);
    if (user.length === 0) {
      return page({ userName: name, posts: [], notFound: true });
    }

    const userId = user[0]["id"] as number;
    const posts = find("Post", { user_id: userId, shared: 1 }, [
      "id",
      "title",
      "content",
      "shared",
      "share_password",
    ]);

    if (posts.length === 0) {
      return page({ userName: name, posts: [], notFound: true });
    }

    return page({
      userName: name,
      posts: posts.map((post) => ({
        id: post["id"] as string,
        title: post["title"] as string,
        content: post["content"] as string,
        shared: post["shared"] === 1,
        hasPassword: Boolean(post["share_password"]),
      })),
      notFound: false,
    });
  },
});

export default define.page((props: PageProps<UserPageProps>) => {
  const { userName, posts, notFound } = props.data;

  if (notFound) {
    return (
      <>
        <Head>
          <title>Not Found</title>
        </Head>
        <PageContainer centered>
          <div className="absolute top-3 right-3">
            <ThemeToggle />
          </div>
          <span className="text-xl text-gray-500 dark:text-gray-400">
            Page not found
          </span>
        </PageContainer>
      </>
    );
  }

  return (
    <>
      <Head>
        <title>{userName}'s Posts</title>
      </Head>
      <PageContainer>
        <div className="absolute top-3 right-3">
          <ThemeToggle />
        </div>
        <h1 className="text-2xl font-bold mt-2">{userName}'s Posts</h1>
        <PostList posts={posts} readOnly />
      </PageContainer>
    </>
  );
});
